package com.dp.mallchat;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;

public class XMLParserExample {
    public static void main(String[] args) {
        String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ESBRESP><HEADER><CODE>100</CODE><MSG>OK</MSG></HEADER><XMLDATA><![CDATA[]]></XMLDATA></ESBRESP>";

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            Document document = builder.parse(new InputSource(new StringReader(xmlString)));
            document.getDocumentElement().normalize();

            NodeList codeNode = document.getElementsByTagName("CODEs");
            NodeList msgNode = document.getElementsByTagName("MSG");
            if (codeNode.getLength() > 0 && msgNode.getLength() > 0) {
                Element codeElement = (Element) codeNode.item(0);
                Element msgElement = (Element) msgNode.item(0);
                String code = codeElement.getTextContent();
                System.out.println("Tag code value: " + code);
                String msg = msgElement.getTextContent();
                System.out.println("Tag msg value: " + msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}